package com.api.gbhg.liuwenbo.api;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.api.gbhg.liuwenbo.action.AmountVerification;
import com.google.common.base.Joiner;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 金额验证Api
 */
@Path("/gb/VC")
public class AmountVerificationApi {

    private static final String czjl = "uf_dfczbkxmjl"; //记录表
    private static final String czbk = "uf_dfczbkxm"; //数据源表
    private int thisYear = LocalDate.now().getYear();
    private int lastYear = LocalDate.now().getYear()-1;
    private Map<String,Object> msgMap = new HashMap<>();

    @POST
    @Path("/Verification")
    @Produces(MediaType.APPLICATION_JSON)
    public String Verification(Map<String,Object> param){
//        String requestid = param.get("requestid").toString();

//        Integer nd = (Integer) param.get("nf");

        String sn = param.get("sn").toString();

        String dn = param.get("dn").toString();

        Integer dw = (Integer) param.get("dw");
        Integer ysnd = (Integer) param.get("ysnd");

        Map<String,Object> dnMap = arrtoMap2(dn);
        Map<String,Object> snMap = arrtoMap2(sn);

        Map<String,Object> msgMap1 = AmountVerification.MoneyVc2(dnMap,ysnd,dw,ysnd,"dn");
        Map<String,Object> msgMap2 = AmountVerification.MoneyVc2(snMap, ysnd-1,dw,ysnd,"sn");

        msgMap.putAll(msgMap1);
        msgMap.putAll(msgMap2);
        msgMap.remove("code");

        if (msgMap1.get("code").toString().equals("200")&&msgMap2.get("code").toString().equals("200")){
            msgMap.put("code","200");
            return JSON.toJSONString(msgMap);
        }else{
            StringBuffer sb = new StringBuffer();
            HashMap<String,Object> TipsMap =  new HashMap<>();
            for (Map.Entry<String, Object> entry : msgMap.entrySet()) {
                sb.append(entry.getKey()+" |");
            }
            TipsMap.put("code","300");
            TipsMap.put("msg",sb.toString());
            return JSON.toJSONString(TipsMap);
        }


//        boolean vcResult = getVcResult(sn,dn, nd, requestid);
//        if (vcResult){
//            msgMap.put("success","true");
//        }else{
//            msgMap.put("success","false");
//        }

    }



    public boolean getVcResult(String strSn, String strDn, int nd, String requestid){
        boolean success1 = true;
        boolean success2 = true;
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        try {
            if (StrUtil.isNotEmpty(strSn)){

            String[] sn = strSn.split(",");//”1:10.23,...,.."
            //项目id
            Integer[] snxmid = getxmid(sn);
            //取差
            List<Integer> snlist = getDifference(snxmid);
            if (snlist.size()>0){
                String ids = Joiner.on(",").join((Iterable<?>) snlist);
                String sql = " insert into "+czjl+"(requestid,xmmc,nd,yjsr,jzje,xmid) select ("+requestid+") requestid,xmmc,nf,yjsrwy,jzjewy,id from uf_dfczbkxm where id in ("+ids+") ";
                rst.execute(sql);
            }
            Map<Integer, Object> snMap = arrtoMap(sn);
            boolean snIsSuccess = MoneyVc(snMap,nd-1,snxmid);
            if(snIsSuccess){
                StringBuilder sb1 = new StringBuilder();
                sb1.append(" update uf_dfczbkxmjl set jzje = (case "); //上年
                for (Map.Entry<Integer,Object> entry: snMap.entrySet()) {
                    sb1.append(" when xmid = "+entry.getKey()+" then jzje - "+entry.getValue()+" ");
                }
                sb1.append(" else jzje end) where xmid in ("+Joiner.on(",").join((Iterable<?>) Arrays.asList(snxmid))+")");
                boolean s1 = rst.executeUpdate(sb1.toString());
                if (s1){
                    success1 = true;
                }else{
                    success1 = false;
                }
            }
            }

            if (StrUtil.isNotEmpty(strDn)){

            String[] dn = strDn.split(",");
            Integer[] dnxmid = getxmid(dn);
            List<Integer> dnlist = getDifference(dnxmid);
            if (dnlist.size()>0){
                String ids = Joiner.on(",").join((Iterable<?>) dnlist);
                String sql = " insert into "+czjl+"(requestid,xmmc,nd,yjsr,jzje,xmid) select ("+requestid+") requestid,xmmc,nf,yjsrwy,jzjewy,id from uf_dfczbkxm where id in ("+ids+") ";
                rst.execute(sql);
            }
            Map<Integer, Object> dnMap = arrtoMap(dn);
            boolean dnIsSuccess = MoneyVc(dnMap,nd,dnxmid);
            if (dnIsSuccess){
                StringBuilder sb2 = new StringBuilder();
                sb2.append(" update uf_dfczbkxmjl set yjsr = (case "); //本年
                for (Map.Entry<Integer,Object> entry: dnMap.entrySet()) {
                    sb2.append(" when xmid = "+entry.getKey()+" then yjsr - "+entry.getValue()+" ");
                }
                sb2.append(" else yjsr end) where xmid in ("+Joiner.on(",").join((Iterable<?>) Arrays.asList(dnxmid))+")");
                boolean s2 = rst.executeUpdate(sb2.toString());
                if (s2){
                    success2 = true;
                }else{
                    success2 = false;
                }
            }
            }
        } catch (Exception e) {
            rst.rollback();
            msgMap.put("msg","500");
            e.printStackTrace();
            rst.rollback();
        }
        boolean issuccess = false;
        if (success1&&success2){
            rst.commit();
            issuccess = true;
        }else{
            rst.rollback();
        }

        return issuccess;
    }

    /**
     * 从数组中截取id
     * @param arr
     * @return
     */
    public Integer[] getxmid(String[] arr){
        Integer[] id = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            String[] split = arr[i].split(":");
            id[i] = Integer.valueOf(split[0]);
        }
        return id;
    }

    /**
     * 金额校验
     * @param param
     * @param nd
     * @param id
     * @return
     */
    public boolean MoneyVc(Map<Integer, Object> param,int nd,Integer[] id){
        String je ;
        if (nd == thisYear){
            je = "yjsr";
        }else{
            je = "jzje";
        }

        boolean IsIn = IsInsufficientMoney(param, nd, id);
        if (!IsIn)
            return false;


        RecordSet rs = new RecordSet();
        String sql = " select xmid,yjsr,jzje from uf_dfczbkxmjl where xmid in ("+Joiner.on(",").join((Iterable<?>) Arrays.asList(id))+")";
        rs.executeQuery(sql);


        Map<Integer,Object> map = new HashMap<>();
        while (rs.next()){
            map.put(rs.getInt("xmid"),rs.getDouble(je));
        }
        boolean isSuccess = true;
        if (map.size()>0){
            for (Map.Entry<Integer,Object> entry: param.entrySet()) {
                String m = map.get(entry.getKey()).toString();//获取数据库记录的金额
                Double val = Double.valueOf(m);
                if (val - (Double.valueOf(entry.getValue().toString())) < 0){
                    msgMap.put("xmid",entry.getKey().toString());
                    isSuccess = false;
//                break;
                }
            }
        }else{
            for (Map.Entry<Integer,Object> entry: param.entrySet()) {
                if ((Double.valueOf(entry.getValue().toString())) < 0){
                    msgMap.put("xmid",entry.getKey().toString());
                    isSuccess = false;
                }
            }
        }
        return isSuccess;
    }

    public boolean IsInsufficientMoney(Map<Integer, Object> param,int nd,Integer[] id){
        RecordSet rs = new RecordSet();
        String je ;
        if (nd == thisYear){
            je = "yjsrwy";
        }else{
            je = "jzjewy";
        }
        String sql = " select id,"+je+" from uf_dfczbkxm where id in ("+Joiner.on(",").join((Iterable<?>) Arrays.asList(id))+") ";
        rs.executeQuery(sql);

        Map<Integer,Object> map = new HashMap<>();
        while (rs.next()){
            map.put(rs.getInt("id"),rs.getDouble(je));
        }
        boolean isSuccess = true;
        for (Map.Entry<Integer,Object> entry: param.entrySet()) {
            String m = map.get(entry.getKey()).toString();//获取数据库记录的金额
            Double val = Double.valueOf(m);
            if (val - (Double.valueOf(entry.getValue().toString())) < 0){
                msgMap.put("xmid",entry.getKey().toString());
                isSuccess = false;
            }
        }
        return isSuccess;
    }

    /**
     * 取差
     * @param id
     * @return
     */
    public List<Integer> getDifference(Integer[] id){
        RecordSet rs = new RecordSet();
        String sql = " select xmid from uf_dfczbkxmjl ";
        rs.executeQuery(sql);
        List<Integer> list = new ArrayList<>();
        while (rs.next()){
            list.add(rs.getInt("xmid"));
        }
        List<Integer> arrList = Arrays.asList(id);
        List<Integer> collect = arrList.stream().filter(item -> !list.contains(item)).collect(Collectors.toList());
        return collect;
    }

    /**
     * 数组转map 并且如果存在相同的key 那么value则相加
     * @param arr
     * @return
     */
    public Map<Integer, Object> arrtoMap(String[] arr){//arr:"'1:20.00','2:11.12','1:4.00',...."
        Map<Integer,Object> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            String[] split = arr[i].split(":");
            Integer s1 = Integer.valueOf(split[0]);
            if(map.get(s1)!=null){
                map.put(s1,(Double.valueOf(split[1])+ Double.valueOf(map.get(s1).toString())));
            }else{
                map.put(s1,split[1]);
            }
        }
        return map;
    }

    /**
     * 数组转map 并且如果存在相同的key 那么value则相加
     * @param str
     * @return
     */
    public Map<String, Object> arrtoMap2(String str){//arr:"'1@23:20.00',...."  0,10_1:100
        Map<String,Object> map = new HashMap<>();
        if (StrUtil.isNotEmpty(str)){
            String[] arr = str.split(",");//[1@23:20.00,0@9_7:20.00]
            for (int i = 0; i < arr.length; i++) {
                String[] idx_id = arr[i].split(":");//1@23 | 0@9_7
                String[] split1 = idx_id[0].split("@");

                if (map.containsKey(split1[0]+","+split1[1])){
                    BigDecimal n1 = new BigDecimal(map.get(split1[0]+","+split1[1]).toString());
                    BigDecimal n2 = new BigDecimal(idx_id[1]);
                    map.put(split1[0]+","+split1[1],n1.add(n2));
                }else{
                    map.put(split1[0]+","+split1[1],idx_id[1]);
                }

                /*if (split1.length>1){
                    if(map.get(split1[0]+","+split1[1])!=null){
                        map.put(split1[0]+","+split1[1],(Double.valueOf(idx_id[1])+ Double.valueOf(map.get(split1[0]+","+split1[1]).toString())));
                    }else{
                        map.put(split1[0]+","+split1[1],idx_id[1]);
                    }
                }else{
                    if(map.get(split1[0]+",")!=null){
                        map.put(split1[0]+",",(Double.valueOf(idx_id[1])+ Double.valueOf(map.get(split1[0]+",").toString())));
                    }else{
                        map.put(split1[0]+",",idx_id[1]);
                    }
                }*/
            }
        }
        return map;
    }

    public String getDatas(int xmid,double money,int nd){
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        String sql = "select * from uf_dfczbkxmjl where xmid = "+xmid+" and  ";
        return null;
    }

    /**
     * 获取对应的地方政府拨款项目金额
     * @param xmid
     * @param nd
     * @return
     */
    public double getDfczbkxm(int xmid,int nd){
        RecordSet rs = new RecordSet();
        int year = LocalDate.now().getYear();
        String sql ;
        double money;
        if (nd==year){
            sql = " select yjsrwy from uf_dfczbkxm where id = "+xmid+" ";
            rs.executeQuery(sql);
            rs.next();
            money = rs.getDouble("yjsrwy");
        }else{
            sql = " select jzjewy from uf_dfczbkxm where id = "+xmid+" ";
            rs.executeQuery(sql);
            rs.next();
            money = rs.getDouble("jzjewy");
        }
        return money;
    }


    //-----------------------------------------------------------------------------------------------------------------------单个校验
    @POST
    @Path("/singleVc")
    @Produces(MediaType.APPLICATION_JSON)
    public String singleVc(Map<String,Object> param){
        if (!param.containsKey("v") || !param.containsKey("nf")){
            Map<String,Object> map  = new HashMap<>();
            map.put("retcode","-1");
            map.put("retmsg","请检查上送参数！为必填项");
            return JSON.toJSONString(map);
        }
        Integer nf = (Integer) param.get("nf");

        String v = param.get("v").toString();
        String[] split = v.split(",");

        Integer[] xmid = getxmid(split);
        Map<Integer, Object> map = arrtoMap(split);

        boolean isSuccess = MoneyVc(map, nf, xmid);

        if (isSuccess)
            return JSON.toJSONString("true");
        else
            return JSON.toJSONString("false");
    }
}
